﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
using UFramework.Editor;
using NPOI.SS.UserModel;
using System;
using System.Text;
public class ExelTableImporter : EditorWindow
{
    private static string OutPutPath = Application.dataPath;

    [MenuItem("Uframework/TableImport")]
    public static void Import()
    {
        string folderName = EditorUtility.OpenFolderPanel("请选择.xlsx表格所在的文件夹", "/", "");

        string[] excelFiles = Directory.GetFiles(folderName);
        StringBuilder builder_Var = new StringBuilder();
        StringBuilder builder_Fun = new StringBuilder();
        foreach (var item in excelFiles)
        {
            string extention = Path.GetExtension(item).ToLower();
            if (item.Contains("$"))
            {
                continue;//跳过临时文件
            }

            if (extention == ".xlsx" || extention == ".xls")
            {
                //生成读取类和Text文件
                Debug.Log(item);
                HandleTable(item);
                string TABLENAME = Path.GetFileNameWithoutExtension(item);
                builder_Var.AppendLine(CONFIG.tableVar.Replace("[TABLENAME]", TABLENAME));
                builder_Fun.AppendLine(CONFIG.awakeCode.Replace("[TABLENAMESTR]", "\"" + TABLENAME + "\"")
                    .Replace("[TABLENAME]", TABLENAME)
                    ); ;
            }
        }
        StringBuilder builder_Configs = new StringBuilder();
        builder_Configs.AppendLine(CONFIG.classHead);
        builder_Configs.Append(builder_Var);
        builder_Configs.AppendLine(CONFIG.awakeFunctionHead);
        builder_Configs.Append(builder_Fun);
        builder_Configs.AppendLine(CONFIG.ClassEnd);
        string dir = Path.Combine(OutPutPath, "DataTable\\Scripts", "ConfigManager.cs");
        FileHelper.CreatDirBeforeWrite(dir);
        File.WriteAllText(dir, builder_Configs.ToString());
        Debug.Log("配置表导入完成:" + dir);
    }

    public static void HandleTable(string excelFile)
    {
        //对每一个表格生成读取类
        var sheet = ExcelHelper.ReadWorkBook(excelFile).GetSheetAt(0);
        var row0 = sheet.GetRow(0);
        var row1 = sheet.GetRow(1);
        string fileName = Path.GetFileNameWithoutExtension(excelFile);
        GenTableReaderClass("TBR_" + fileName, row0, row1);

        //对每一个表格生成txt文件
        GenTxtFile(sheet, fileName);
    }

    private static void GenTxtFile(ISheet sheet, string tableName)
    {
        StringBuilder builder = new StringBuilder();
        ExcelHelper.ForEveryRow(sheet, row =>
         {
             ExcelHelper.ForEveryCell(row, cell =>
             {
                 if (cell == null)
                 {
                     builder.Append("");
                 }
                 else
                 {
                     builder.Append(cell.ToString());
                 }
                 builder.Append("\t");
                 return true;
             });
             builder.Remove(builder.Length - 1, 1);//移除最后一个\t
             builder.Append("\n");
             return true;
         });
        builder.Remove(builder.Length - 1, 1);//移除最后一个\n
        string dir = Path.Combine(OutPutPath, "DataTable\\Resources\\DataTable", tableName + ".txt");
        FileHelper.CreatDirBeforeWrite(dir);
        File.WriteAllText(dir, builder.ToString());
    }

    private static void GenTableReaderClass(string className, IRow row0, IRow row1)
    {
        StringBuilder builder = new StringBuilder();
        //写类的头
        builder.AppendLine(TBR.classHead.Replace("[ClassName]", className));

        //为每一个字段写Get方法
        foreach (var item in row0.Cells)
        {
            string FNAME = item.ToString();
            //if (FNAME.ToLower() == "id")
            //{
            //    continue;//跳过ID列
            //}
            string RET = row1.GetCell(item.ColumnIndex).ToString().ToLower();
            builder.AppendLine(TBR.functionHead.Replace("[RET]", RET).Replace("[FNAME]", FNAME));

            if (RET == "string")
            {
                builder.AppendLine(TBR.functionEndString.Replace("[FNAME]", string.Format("\"{0}\"", FNAME)));
            }
            else
            {
                builder.AppendLine(TBR.functionEndNumber.Replace("[FNAME]", string.Format("\"{0}\"", FNAME)).Replace("[RET]", RET));
            }
        }

        builder.AppendLine(TBR.classEnd);

        string dir = Path.Combine(OutPutPath, "DataTable\\Scripts", className + ".cs");
        FileHelper.CreatDirBeforeWrite(dir);
        File.WriteAllText(dir, builder.ToString());
    }
    #region 模板字符串
    private class TBR
    {
        public static string classHead = @"
//自动生成的表格读取类
using System.Collections.Generic;
public class [ClassName]
{
    private Dictionary<int, Dictionary<string, string>> datas;

     public void FillDatas(string tableText)
    {
        datas = new Dictionary<int, Dictionary<string, string>>();

        //获取表头
        string[] lines = tableText.Split('\n');
        int index = 0;
        string[] filedNames = lines[index++].Split('\t');//字段名称
        index++;//跳过类型
        index++;//跳过其他信息
        index++;//跳过中文表头

        for (; index < lines.Length; index++)
        {
            if (string.IsNullOrWhiteSpace(lines[index]))
            {
                continue;
            }

            string[] filedValues = lines[index].Split('\t');//字段名称
            var kvDic = new Dictionary<string, string>();
            if (string.IsNullOrWhiteSpace(filedValues[0]))
            {
                UnityEngine.Debug.LogWarning(index);
                continue;
            }
    datas.Add(int.Parse(filedValues[0]), kvDic);

            for (int i = 0; i<filedValues.Length; i++)//从1开始则跳过ID,前提是第0列必须是ID
            {
                kvDic.Add(filedNames[i], filedValues[i]);
            }
        }
    }
";
        public static string classEnd = "}";

        public static string functionHead = @"
public  [RET] Get[FNAME](int id){
";
        public static string functionEndString = @"
    return  datas[id][[FNAME]];
}
";

        public static string functionEndNumber = @"
    return [RET].Parse(datas[id][[FNAME]]);
}
";
    }
    private class CONFIG
    {
        public static string classHead = @"
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ConfigManager : MonoBehaviour
{
";
        public static string tableVar = @"
    public static TBR_[TABLENAME] t[TABLENAME] = new TBR_[TABLENAME]();
";
        public static string awakeFunctionHead = @"
    private void Awake()
    {
";
        public static string awakeCode = @"
 t[TABLENAME].FillDatas(LoadTableText([TABLENAMESTR]));
";
        public static string ClassEnd = "  } " +
            "private string LoadTableText(string resourcesName)" +
            "{ " +
            "   return Resources.Load<TextAsset>(\"DataTable/\" + resourcesName).text; " +
            "}" +
            "}";
    }

    #endregion 模板字符串
}